package com.xenione.libs.swipemaker.orientation;


import ohos.agp.components.Component;
import ohos.multimodalinput.event.TouchEvent;

/**
 * Created by Eugeni on 28/09/2016.
 */
public class HorizontalOrientationStrategy extends OrientationStrategy {

    private int mLastTouchX;
    private int mLastTouchY;
    private boolean mIsDragging;

    private Component mView;

    public HorizontalOrientationStrategy(Component view) {
        super(view);
        mView = view;
    }

    public HorizontalOrientationStrategy(Component view, int slopTouch) {
        super(view, slopTouch);
        mView = view;
    }

    @Override
    public boolean onTouchEvent(TouchEvent event) {

        final int action = event.getAction();
        if (action == TouchEvent.CANCEL || action == TouchEvent.PRIMARY_POINT_UP) {
            if (mIsDragging) {
                disallowParentInterceptTouchEvent(false);
            }
            fling();
            isCheckTouch = false;
            mIsDragging = false;
            return true;
        }
        switch (action) {
            case TouchEvent.PRIMARY_POINT_DOWN: {
                mLastTouchX = (int)event.getPointerScreenPosition(0).getX();
                mLastTouchY = (int)event.getPointerScreenPosition(0).getY();

                break;
            }
            case TouchEvent.POINT_MOVE: {
                if(mLastTouchX < mTouchSlop && !mIsDragging){
                    disallowParentInterceptTouchEvent(false);
                    return false;
                }

                int deltaX = (int) event.getPointerScreenPosition(0).getX() - mLastTouchX;
                int deltaY = (int) event.getPointerScreenPosition(0).getY() - mLastTouchY;

                if(!isCheckTouch) {
                    isCheckTouch = true;
                    if (Math.abs(deltaY) > Math.abs(deltaX)) {
                        disallowParentInterceptTouchEvent(true);
                        mIsDragging = false;
                        return true;
                    } else {
                        disallowParentInterceptTouchEvent(false);
                        mIsDragging = true;
                    }
                }

                if (mIsDragging) {
                    translateBy(deltaX);
                    mLastTouchX = (int) event.getPointerScreenPosition(0).getX();
                }

                break;
            }
        }

        return true;
    }

    @Override
    int getDelta() {
        return (int) mView.getTranslationX();
    }

    @Override
    void setDelta(int delta) {
        mView.setTranslationX(delta);
    }
}